package Dao;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CreateEntity {
    public static void main(String[] args) throws SQLException, IOException {
           List tables=GetTables();
        for (Object string:tables) {
            getColumns(string.toString());
        }
        }
        /*
        * 获取每张表的列信息
        * 列名字 属性
        * */
        public static void  getColumns(String tableName) throws SQLException, IOException {
            String sql="DESC "+tableName;
            Map<String,String> map=new HashMap<>();//存列名 和属性
            BaseDao baseDao=new BaseDao();
            ResultSet resultSet=baseDao.executeQuery(sql,new Object[0]);
            while(resultSet.next()){
                String Field = resultSet.getString("Field");
                String Type = resultSet.getString("Type");
                map.put(Field,Type);
            }
            resultSet.close();
            createEntity(tableName,map);
        }
        /*
        * 创建新文件  .java
        * */
        public static void createEntity(String tname,Map<String,String> map) throws IOException {
            //使用字符流创建文件
            tname=tname.substring(0,1).toUpperCase()+tname.substring(1);
            Writer writer=new FileWriter(".java");
            writer.write("public class "+tname+"{\n");
            for(Map.Entry<String,String> entry:map.entrySet()){
                writer.write("\t private ");
                String value=entry.getValue();
                if(value.indexOf("int")!=-1){
                    writer.write("{\t int");
                }else if(value.indexOf("char")!=-1){
                    writer.write("{\t char");
                }else if(value.indexOf("datetime")!=-1 || value.indexOf("date")!=-1){
                    writer.write("\t Date");
                }else if(value.indexOf("double")!=-1){
                    writer.write("{\t Double");
                }else if(value.indexOf("boolean")!=-1){
                    writer.write("{\t boolean");
                }
                writer.write("\t"+entry.getKey()+";\n");
            }
            writer.write("public "+tname+"(){}");
            writer.write("}");
        }
        /*
        * 获取数据库中的表
        * @param tname 表名
        * @param map 列名 和属性
        * */
        public static List GetTables() throws SQLException{
            List<String> table=new ArrayList<>();
            BaseDao baseDao=new BaseDao();
            //第一步 先获取所有的表名、
            String sql="SHOW TABLES;";
            ResultSet resultSet=baseDao.executeQuery(sql,new Object[0]);
            while (resultSet.next()){
                String name=resultSet.getString("Tables_in_shiti");
                System.out.println(name);
            }
            resultSet.close();
            return table;
        }
    }
